package com.qfedu.hotelssm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.qfedu.hotelssm.dao.FixedAssetsDao;
import com.qfedu.hotelssm.dto.FixedAssetsDto;
import com.qfedu.hotelssm.entity.FixedAssets;
import com.qfedu.hotelssm.service.intf.FixedAssetsService;
import com.qfedu.hotelssm.util.StringUtil;
import com.qfedu.hotelssm.vo.PageBean;
import com.qfedu.hotelssm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class FixedAssetsServiceImpl implements FixedAssetsService {
    @Autowired
    private FixedAssetsDao dao;

    @Override
    public R save(FixedAssets fixedAssets) {
        if(dao.save(fixedAssets)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R delete(int id) {
        if(dao.delete(id)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R update(FixedAssets fixedAssets) {
        if(dao.update(fixedAssets)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public PageBean selectPage(String info, int page, int limit) {
        if(StringUtil.isNotEmpty(info)){
            info="%"+info+"%";
        }
        int start=(page-1)*limit;
        return new PageBean((int) dao.selectCount(info),dao.selectPage(info,start,limit));
    }

    @Override
    public R deleteByIds(int[] ids) {
        if (ids != null) {
            if (dao.deleteByIds(ids) > 0) {
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public List<FixedAssetsDto> download() {
        return dao.all();
    }

    @Override
    public R upload(MultipartFile file) throws IOException {
        //1.接收文件， 获取文件内容
        //1.验证上传文件是否存在
        if(!file.isEmpty()){
            //2.解析Excel -EasyExcel
            //2.解析Excel数据
            List<FixedAssets> list= EasyExcel.read(file.getInputStream(), FixedAssets.class, new ReadListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {}
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
            }).sheet().doReadSync();
            //3.Mybatis 实现批量新增
            if(dao.saveBatch(list)>0){
                //4.返回
                return R.ok();
            }
        }
        return R.fail();
    }


}
